package com.wgj.android.zfp;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.jiaai.xui.utils.XAppUtils;
import com.wgj.android.R;
import com.wgj.android.accesslibility.config.WXConfginUtil;
import com.wgj.android.http.WeiXinEvents;
import com.wgj.android.http.weixin.WXFormatUtil;
import com.wgj.android.http.weixin.WXHttp;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.event.CleanEvent;
import com.wgj.android.http.weixin.model.CleanInfo;
import com.wgj.android.http.weixin.model.WXFriend;
import com.wgj.android.http.weixin.model.WXInfo;
import com.wgj.android.ui.activity.CleanFriednsActivity;

import org.greenrobot.eventbus.EventBus;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/11/27.
 */

public class WXCleanService extends Service {
    private  static  String TAG="WXCleanService";
    private  CleanInfo cleanInfo;
    private  static  int cleanNum=0;
    private  static   boolean isStartCleanTask=false;

    private  static  CleanFirendsTaskManagerThread cleanFirendsTaskManagerThread;
    private  static ModifyTaskThread modifyTaskThread;
    private  List<WXFriend> wxFriends=new ArrayList<>();
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(!isStartCleanTask){
            try {

                Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
                Intent nfIntent = new Intent(this, CleanFriednsActivity.class);
                builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                        .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.logo)) // 设置下拉列表中的图标(大图标)
                        .setContentTitle("旺旺通") // 设置下拉列表里的标题
                        .setSmallIcon(R.mipmap.logo) // 设置状态栏内的小图标
                        .setContentText("旺旺通微信清粉助手") // 设置上下文内容
                        .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

                Notification notification = builder.build(); // 获取构建好的Notification
                notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
                startForeground(112, notification);

                //每次开始清粉任务时就清空队列以防重复发送的情况
                CleanFirendsTaskManager.getInstance().clear();
                cleanFirendsTaskManagerThread=new CleanFirendsTaskManagerThread();
                modifyTaskThread=new ModifyTaskThread();
                cleanInfo=WeiXinCacheUtil.getCleanInfo(WeiXinCacheUtil.getInfo().getWxuin());
                new Thread(new getFrindesThread()).start();
            }catch (Exception e){
                Log.e(TAG,e.getMessage());
            }
        }
         return super.onStartCommand(intent, flags, startId);
    }
    private  class   getFrindesThread implements Runnable{

        @Override
        public void run() {
            try {
                EventBus.getDefault().postSticky(new CleanEvent("",CleanEvent.type.LOGIND));
                boolean isRun=true;
                String seq="0";
                while (isRun){
                    Log.e(TAG,"seq——-----seq:"+seq);
                    seq= getRun(seq);
                    if("0".equals(seq)){
                        isRun=false;
                    }
                }
                if(WXConfginUtil.isOpenCleanFirendFilter() && cleanInfo.getNickNames().size()==wxFriends.size()){
                    EventBus.getDefault().post(new CleanEvent(""+wxFriends.size(),CleanEvent.type.LOGIND_END));
                    XAppUtils.stopRunningService(WXCleanService.class.getName());
                    return;
                }
                startClean();
                new Thread(cleanFirendsTaskManagerThread).start();

            } catch (Exception e) {
                e.printStackTrace();
                XAppUtils.stopRunningService(WXCleanService.class.getName());
            }
        }
    }
    @Override
    public void onDestroy() {
        cleanFirendsTaskManagerThread=null;
        modifyTaskThread=null;
        isStartCleanTask=false;
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        super.onDestroy();
    }
    private String getRun(final String Seq) throws  Exception{
        WeiXinCacheUtil.saveStatus(WeiXinEvents.EventsType.GETINGCONTACT);
        final WXInfo wxInfo = WeiXinCacheUtil.getInfo();
        String url = "http://" + wxInfo.getBaseUrl() + "/cgi-bin/mmwebwx-bin/webwxgetcontact?" +
                "r=".concat("" + new Date().getTime()) +
                "&seq=".concat(Seq) +
                "&skey=".concat(wxInfo.getSkey());

        String res = WXHttp.obtain().syncPost(url, "{}");
        try {
            JSONObject jsonObject=null;
            jsonObject =JSONObject.parseObject(res);

            List<WXFriend> w=WXFormatUtil.getAllName(jsonObject, wxInfo);
            Log.e(TAG,"读取到好友数量:"+w.size());
            wxFriends.addAll(w);

            return  jsonObject.getString("Seq");
        }catch (Exception e){
            Log.e(TAG,"拉取通讯录异常!"+e.getMessage());
            stopSelf();
            return "0";

        }
    }

    public  void  startClean(){
        EventBus.getDefault().post(new CleanEvent(""+wxFriends.size(),CleanEvent.type.LOGIND_END));
        int size=WXConfginUtil.getCheckNumber();
        for(WXFriend f:wxFriends){
            CleanFirendsTask task=new CleanFirendsTask(f.getUserName(),f.getNickName(),f.getHeadImgUrl());
            if(WXConfginUtil.isOpenCleanFirendFilter()){
                if(!cleanInfo.getNickNames().contains(f.getNickName())){
                    if(CleanFirendsTaskManager.getInstance().getSize()<size){
                         CleanFirendsTaskManager.getInstance().addCleanFiredsTask(task);
                    }else {
                        break;
                    }

                }
            }else {
                if(CleanFirendsTaskManager.getInstance().getSize()<size){
                    CleanFirendsTaskManager.getInstance().addCleanFiredsTask(task);
                }else {
                    break;
                }

            }

        }


    }

    public  static  void  stop(){
        cleanFirendsTaskManagerThread.isStop=true;
        modifyTaskThread.isStop=true;
        isStartCleanTask=false;
        XAppUtils.stopRunningService(WXCleanService.class.getName());

    }



    class CleanFirendsTaskManagerThread implements Runnable {
        private ExecutorService pool;
        // 线程池大小
        private final int POOL_SIZE = 1;
        // 轮询时间
        private final int SLEEP_TIME = 2500;
        // 是否停止
        private boolean isStop = false;


        public CleanFirendsTaskManagerThread() {
            pool = Executors.newFixedThreadPool(POOL_SIZE);
        }

        @Override
        public void run() {
            while (!isStop) {
                CleanFirendsTask clieanTask = CleanFirendsTaskManager.getInstance().getCleanFirendTask();
                if (clieanTask != null) {
                    Log.d(TAG,"start task"+clieanTask.getToNickName()+"USER_ID:"+clieanTask.getToUserName());
                    pool.execute(clieanTask);
                    try {
                        // 查询任务完成失败的,重新加载任务队列
                        // 轮询,
                        Thread.sleep(SLEEP_TIME);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }else {
                    isStop=true;
                }

            }
            pool.shutdown();
            new Thread(modifyTaskThread).start();//启动更改备注的线程
            EventBus.getDefault().post(new CleanEvent(""+CleanFirendsTaskManager.getInstance().getModifyTaskSize(),CleanEvent.type.START_CLEAN));
        }


    }
    class ModifyTaskThread implements Runnable {

        private ExecutorService pool;
        // 线程池大小
        private final int POOL_SIZE = 1;
        // 轮询时间
        private final int SLEEP_TIME = 11000;
        // 是否停止
        private boolean isStop = false;

        public ModifyTaskThread() {
            pool = Executors.newFixedThreadPool(POOL_SIZE);

        }

        @Override
        public void run() {
            int size=CleanFirendsTaskManager.getInstance().getModifyTaskSize();
            while (!isStop) {
                try{
                    ModifyTask modifyTask = CleanFirendsTaskManager.getInstance().getModifyTask();
                    if (modifyTask != null) {
                        Log.d(TAG, "开始备注:" + modifyTask.getToNickName().concat("  ").concat(new SimpleDateFormat("HH:mm:ss").format(new Date())));//todo delete
                        pool.execute(modifyTask);
                        try {
                            Thread.sleep(SLEEP_TIME);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else {
                        isStop=true;
                    }
                }catch (Exception e){
                    isStop=true;
                }

            }
            pool.shutdown();
            try {
                Thread.sleep(1000*10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new CleanEvent("",CleanEvent.type.STOP_CLEAN));
            XAppUtils.stopRunningService(WXCleanService.class.getName());
        }


    }
}
